#Include "Protheus.ch"
#Include "TbiConn.ch"

User Function MDDJ0020()
Local aArquivos := {}
Local aRecord := {}
Local aSZEArea := {}
Local cExtBusca := "*.CSV"
Local cCamBusca := ""
Local nQtdReg := 0

RpcSetType(3)
PREPARE ENVIRONMENT EMPRESA "99" FILIAL "01"
aSZEArea := SZE->(GetArea())
ConOut("[" + DToC(Date()) + " " + Time() + "] ####### INTEGRACAO MEDIDORES - IMPORTA DADOS #######")
ConOut("[" + DToC(Date()) + " " + Time() + "] IMPORTA DADOS MEDIDOR DISTRIBUICAO...")
cCamBusca := GetSrvProfString("Startpath", "") + "\MEDIDOR\D2W\DATA\"
AEval(Directory(cCamBusca + cExtBusca), {|x| IF(x[3] == Date(), AAdd(aArquivos, Upper(x[1])),)})
nQtdReg := Len(aArquivos)

dbSelectArea("SZE")
SZE->(dbSetOrder(2))  // ZE_FILIAL+DTOS(ZE_DATA)+ZE_HORA+ZE_ROTA+ZE_FRETEIR

For nI := 1 To nQtdReg
	FT_FUSE(cCamBusca + aArquivos[nI])
	FT_FGOTOP()
	ConOut("[" + DToC(Date()) + " " + Time() + "] LENDO ARQUIVO: " + aArquivos[nI])
	
	While !FT_FEOF()
		cLinha := FT_FREADLN()
		aRecord := Separa(cLinha, ";")
		
		IF !SZE->(dbSeek(xFilial("SZE") + DToS(CToD(SubStr(aRecord[01], 01, 10))) + SubStr(aRecord[01], 12, 08) + PadR(aRecord[02], TAMSX3("ZE_ROTA")[1]) + PadR(aRecord[03], TAMSX3("ZE_FRETEIR")[1])))
			SZE->(RecLock("SZE", .T.))
				SZE->ZE_FILIAL := xFilial("SZE")
				SZE->ZE_DATA := CToD(SubStr(aRecord[01], 01, 10))
				SZE->ZE_HORA := SubStr(aRecord[01], 12, 08)
				SZE->ZE_ROTA := aRecord[02]
				SZE->ZE_FRETEIR := aRecord[03]
				SZE->ZE_VOLMED := Val(aRecord[05])
				SZE->ZE_TEMP := Val(StrTran(aRecord[06], ",", "."))
				SZE->ZE_VOLINF := Val(aRecord[04])
			SZE->(MsUnLock())
		EndIF
		FT_FSKIP()
	End
	ConOut("[" + DToC(Date()) + " " + Time() + "] FIM DA LEITURA DO ARQUIVO: " + aArquivos[nI])
	FT_FUSE()
Next nI

SZE->(dbCloseArea())
RestArea(aSZEArea)

RESET ENVIRONMENT
Return Nil